package com.warmheart.base.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.warmheart.core.enums.PlatEnum.MobileMsgTypeEnum;
import com.warmheart.model.CheckResultModel;

/**
 * 
 * @ClassName: AliSmsService
 * @Description: 阿里云短信验证码服务
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
public abstract class AliSmsService implements IWhConfigService<AliSmsConfig> {

    private final static Logger log = LoggerFactory.getLogger(AliSmsService.class);

    private final StringRedisTemplate stringRedisTemplate;

    public AliSmsService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 
     * @Title: sendSms
     * @Description: 发送短信
     * @author ZhangJianyang
     * @param userPhone
     * @param templateCode
     * @param templateParam
     * @return
     */
    private boolean sendSms(String userPhone, String templateCode, String templateParam) {

        boolean result = false;
        try {
            // 初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile(config().getRegionId(), config().getAccessKeyId(),
                    config().getAccessKeySecret());
            DefaultProfile.addEndpoint(config().getRegionId(), config().getProduct(), config().getEndpoint());
            IAcsClient acsClient = new DefaultAcsClient(profile);

            // 组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            // 必填:待发送手机号
            request.setPhoneNumbers(userPhone);
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName(config().getSignName());
            // 必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            // 可选:模板中的变量替换JSON串,如"{\"code":"1234"\}"
            if (StringUtils.isNotBlank(templateParam)) {
                request.setTemplateParam(templateParam);
            }
            log.info("短信接口发送手机号码:" + userPhone);
            log.info("短信接口发送变量:" + templateParam);
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null) {
                log.info("短信接口返回code:" + sendSmsResponse.getCode());
            }
            // 发送成功
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                result = true;
            }
        } catch (Exception e) {
            log.error("验证码发送失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 
     * @Title: sendLoginMsg
     * @Description: 发送登录验证码
     * @author ZhangJianyang
     * @param phone
     * @param code
     * @return
     */
    public boolean sendLoginMsg(String phone, String code) {
        Map<String, String> tempMap = new HashMap<String, String>();
        tempMap.put(config().getVerificationCodeKey(), code);
        return sendSms(phone, config().getVerificationCode(), JSONObject.toJSONString(tempMap));
    }

    // 判断一个手机号能否发验证码短信
    public CheckResultModel checkPhone(String phone, MobileMsgTypeEnum mobileMsgTypeEnum) {
        CheckResultModel checkResult = new CheckResultModel();
        if (StringUtils.isBlank(phone)) {
            checkResult.setCheckFlag(false);
            checkResult.setCheckMsg("手机号码不可为空");
            return checkResult;
        }
        List<String> keyList = new ArrayList<String>();
        keyList.add(mobileMsgTypeEnum.getValue() + phone);
        keyList.add(config().getSendSeconds());
        keyList.add(config().getDayCnt());
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("smslimit.lua")));
        redisScript.setResultType(String.class);
        String result = null;
        try {
            result = stringRedisTemplate.execute(redisScript, keyList);
        } catch (Exception e) {
            log.error("校验手机号码异常：" + e.getMessage(), e);
            checkResult.setCheckFlag(false);
            checkResult.setCheckMsg("系统异常");
            return checkResult;
        }
        if (StringUtils.isBlank(result)) {
            checkResult.setCheckFlag(false);
            checkResult.setCheckMsg("该号码暂不可发送验证码");
            return checkResult;
        }
        if ("1".equals(result)) {
            checkResult.setCheckFlag(true);
            checkResult.setCheckMsg("验证通过");
            return checkResult;
        }
        if ("0".equals(result)) {
            checkResult.setCheckFlag(false);
            checkResult.setCheckMsg("请超过" + config().getSendSeconds() + "秒之后再发短信");
            return checkResult;
        }
        if ("2".equals(result)) {
            checkResult.setCheckFlag(false);
            checkResult.setCheckMsg("当前手机号日内发送数量已超限制");
            return checkResult;
        }
        checkResult.setCheckFlag(false);
        checkResult.setCheckMsg("该号码暂不可发送验证码");
        return checkResult;
    }
}
